package com.wzh.house.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wzh.common.utils.R;
import com.wzh.house.dao.HouseAttrValueDao;
import com.wzh.house.entity.HouseAttrValueEntity;
import com.wzh.house.feign.EsFeign;
import com.wzh.house.vo.AttrValue;
import com.wzh.house.vo.Attrs;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.Query;

import com.wzh.house.dao.NewHouseDao;
import com.wzh.house.entity.NewHouseEntity;
import com.wzh.house.service.NewHouseService;


@Service("newHouseService")
public class NewHouseServiceImpl extends ServiceImpl<NewHouseDao, NewHouseEntity> implements NewHouseService {

    @Autowired
    private NewHouseDao newHouseDao;

    @Autowired
    private HouseAttrValueDao attrValueDao;

    @Autowired
    private EsFeign esFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageUtils checkList(Map<String, Object> params) {
        QueryWrapper<NewHouseEntity> wrapper = new QueryWrapper<>();
        String flag = (String) params.get("flag");
        wrapper.eq("flag",flag);

        String status=(String) params.get("status");
        String houseName=(String) params.get("houseName");

        if (StringUtils.isNotEmpty(status)){
            wrapper.eq("status",status);
        }

        if (StringUtils.isNotEmpty(houseName)){
            wrapper.like("house_name",houseName);
        }

        IPage<NewHouseEntity> page = this.page(
                new Query<NewHouseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public Integer updateStatus(Integer houseId, Integer status) {
        Integer integer = newHouseDao.updateStatus(houseId, status);
        //发布房屋到es
        if (integer>0&&status==6){
            NewHouseEntity newHouse = baseMapper.selectOne(new QueryWrapper<NewHouseEntity>().eq("house_id", houseId));
            HouseAttrValueEntity houseAttr = attrValueDao.selectOne(new QueryWrapper<HouseAttrValueEntity>().eq("house_id", houseId));
            List<AttrValue> attrKeys = JSON.parseObject(houseAttr.getAttrValue(), new TypeReference<List<AttrValue>>() {
            });
            List<Attrs> attrs = new ArrayList<>();
            attrKeys.stream().forEach(item1->{
                List<Attrs> attrss = item1.getParams().stream().filter(item2 -> item2.getSearchFlag() == 1).map(item2 -> {
                    return item2;
                }).collect(Collectors.toList());
                attrs.addAll(attrss);
            });
            newHouse.setAttrs(attrs);
            //feign调用发布到es
            esFeign.upNewHouse(newHouse);
        }
        return integer;
    }

    @Override
    public R esNewList() {
        List<NewHouseEntity> newHouses = baseMapper.selectList(new QueryWrapper<NewHouseEntity>().eq("status", 0).eq("flag",1));
        List<NewHouseEntity> houses = newHouses.stream().map(item -> {
            ArrayList<Attrs> attrs = new ArrayList<>();
            HouseAttrValueEntity houseId = attrValueDao.selectOne(new QueryWrapper<HouseAttrValueEntity>().eq("house_id", item.getHouseId()));
            List<AttrValue> attrKeys = JSON.parseObject(houseId.getAttrValue(), new TypeReference<List<AttrValue>>() {
            });
            attrKeys.stream().forEach(item1->{
                List<Attrs> attrss = item1.getParams().stream().filter(item2 -> item2.getSearchFlag() == 1).map(item2 -> {
                    return item2;
                }).collect(Collectors.toList());
                attrs.addAll(attrss);
            });
            item.setAttrs(attrs);
            return item;
        }).collect(Collectors.toList());
        return R.ok().setData(houses);
    }

    @Override
    public PageUtils selectByUserId(Map<String, Object> params) {
        String userId = (String) params.get("userId");
        IPage<NewHouseEntity> page = this.page(
                new Query<NewHouseEntity>().getPage(params),
                new QueryWrapper<NewHouseEntity>().eq("user_id",userId)
        );
        return new PageUtils(page);
    }

    /**
     * 缓存新房第一页
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        String page1 = (String) params.get("page");

        IPage<NewHouseEntity> houselist = (IPage<NewHouseEntity>) redisTemplate.boundHashOps("newhouse").get("list");
        //先判断是首页并且redis为null 并且key为null 就去查询数据库并存
        if (houselist==null&&Integer.parseInt(page1)==1&& org.apache.commons.lang3.StringUtils.isEmpty(key)){
            IPage<NewHouseEntity> page = this.page(
                    new Query<NewHouseEntity>().getPage(params),
                    new QueryWrapper<NewHouseEntity>()
            );
            System.out.println("查询数据库并缓存第一页");
            redisTemplate.boundHashOps("newhouse").put("list",page);
            redisTemplate.expire("newhouse",10, TimeUnit.SECONDS);
            return new PageUtils(page);
            //else if（再去判断是首页key为null 并且redis有数据）这个就去查询redis缓存
        }else if (houselist!=null&&Integer.parseInt(page1)==1&& org.apache.commons.lang3.StringUtils.isEmpty(key)){

            System.out.println("newhouse缓存命中");
            return  new PageUtils(houselist);

        }else { //else(  去直接查数据库 )
            System.out.println("直接去数据库查newhouse");
            IPage<NewHouseEntity> page = this.page(
                    new Query<NewHouseEntity>().getPage(params),
                    new QueryWrapper<NewHouseEntity>().like("house_name",key).or().like("house_address",key)
            );
            return new PageUtils(page);
        }


    }

    /**
     * 爬虫爬取信息添加数据库
     */
    @Override
    public void papaSave() {
        //1.生成httpclient，相当于该打开一个浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        //2.创建get请求，相当于在浏览器地址栏输入 网址
        HttpGet request = new HttpGet("https://sh.fang.anjuke.com/loupan/all/a1/");//安居客的，地址可换成其他页
        //设置请求后头，将爬虫伪装成浏览器
        request.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36");
          //ip代理 可使用代理IP
          //HttpHost proxy = new HttpHost("139.9.57.163",10001);
          //RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
          //request.setConfig(config);
        try {
            //3.执行get请求，相当于在输入地址栏后敲回车键
            response = httpClient.execute(request);

            //4.判断响应状态为200，进行处理
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //5.获取响应内容
                HttpEntity httpEntity = response.getEntity();
                String html = EntityUtils.toString(httpEntity, "utf-8");
                Document document = Jsoup.parse(html);
                //像js一样，通过标签获取title
                System.out.println(document.getElementsByTag("title").first());
                //像js一样，通过class获取
                Elements elements = document.getElementsByClass("item-mod");
                NewHouseEntity newHouseEntity = new NewHouseEntity();
                for (Element element : elements) {
                    //新房图片
                    Elements select = element.select(".pic img[width='180']");
                    System.out.println(select.attr("src"));
                    newHouseEntity.setDefaultImg(select.attr("src"));
                    //新房名字
                    Elements select1 = element.select(".infos a[class='lp-name']").select(".items-name");
                    System.out.println(select1.text());
                    newHouseEntity.setHouseName(select1.text());
                    //新房价格
                    Elements select2 = element.select(".favor-pos").select(".price");
                    if (select2.size()>0&&!select2.text().contains("万")){
                        String s = select2.text().substring(2, select2.text().indexOf("元"));
                        System.out.println(s);
                        newHouseEntity.setHousePrice(BigDecimal.valueOf(Integer.parseInt(s)));
                    }
                    //新房地址
                    Elements select3 = element.select(".infos a[class='address']").select(".list-map");
                    System.out.println(select3.text());
                    newHouseEntity.setHouseAddress(select3.text());
                    //户型
                    Elements select4 = element.select(".infos a[class='huxing']");
                    if (select4.size()>0&&select4.text().contains("/")){
                        System.out.println(select4.text().substring(4,select4.text().indexOf("/")));
                        newHouseEntity.setHouseDesc(select4.text().substring(4,select4.text().indexOf("/")));
                    }
                    //面积
                    Elements select5 = element.select(".infos a[class='huxing']").select(".building-area");
                    if (select5.text().length()>0){
                        if (!select5.text().contains("-")){
                            String s = select5.text().substring(5, select5.text().indexOf("㎡"));
                            System.out.println(s);
                            newHouseEntity.setHouseArea(BigDecimal.valueOf(Double.valueOf(s)));
                        }else {
                            String s = select5.text().substring(5, select5.text().indexOf("-"));
                            System.out.println(s);
                            newHouseEntity.setHouseArea(BigDecimal.valueOf(Double.valueOf(s)));
                        }

                    }
                    newHouseEntity.setHouseId(0);
                    newHouseEntity.setStatus(1);//状态默认为未卖
                    newHouseEntity.setUserId(0);//默认为管理员添加
                    newHouseEntity.setFlag(1);//新房
                    newHouseEntity.setCreateTime(new Date());//默认为当前时间
                    baseMapper.insert(newHouseEntity);
                }
            } else {
                //如果返回状态不是200，比如404（页面不存在）等，根据情况做处理，这里略
                System.out.println("返回状态不是200");
                System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //6.关闭
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }


    }

}